package com.diudiutechnology.www.yadiudiu.yadiudiu.mine.MyActivity;


import android.content.Context;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.diudiutechnology.www.yadiudiu.util.http.HttpClient;
import com.diudiutechnology.www.yadiudiu.util.http.JsonTools;
import com.diudiutechnology.www.yadiudiu.util.utils.Constant;
import com.diudiutechnology.www.yadiudiu.util.utils.ImgUtils;
import com.diudiutechnology.www.yadiudiu.util.utils.MyProgressDialog;
import com.diudiutechnology.www.yadiudiu.util.utils.PermissionsChecker;
import com.diudiutechnology.www.yadiudiu.util.utils.PictureUtil;
import com.diudiutechnology.www.yadiudiu.util.utils.SelectPhotoPop;
import com.diudiutechnology.www.yadiudiu.util.utils.Sundry;
import com.diudiutechnology.www.yadiudiu.util.utils.ToastUtils;
import com.diudiutechnology.www.yadiudiu.util.view.MerchantsTypePhotoPop;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyActivity.BaseActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyActivity.LoginActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.ApplicationModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.MerchantsTypeModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyApplication;
import com.diudiutechnology.www.yadiudiu.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by Administrator on 2017/8/23.
 * 申请入住
 */

public class ApplicationActivity extends BaseActivity implements View.OnClickListener ,Callback.CommonCallback<String>{
    @Bind(R.id.retur)
    LinearLayout retur;
    @Bind(R.id.merchants_type_layout)//商户类型
    LinearLayout merchants_type_layout;
    @Bind(R.id.merchants_type_text)
    TextView merchants_type_text;

    @Bind(R.id.provincial_layou)//选择地址
            RelativeLayout provincial_layou;
    @Bind(R.id.provincial)
    TextView provincial;

    @Bind(R.id.name)//商户名称
    EditText name;

    @Bind(R.id.legal_name)//法人代表
    EditText legal_name;
    @Bind(R.id.mobilephone)//电话
            EditText mobilephone;
    @Bind(R.id.mail_box)//邮箱
            EditText mail_box;

    @Bind(R.id.specific_address)//详细地址
            EditText specific_address;


    @Bind(R.id.invite)//邀请
            EditText invite;

    @Bind(R.id.id_number)//身份证号
            EditText id_number;


    @Bind(R.id.button)//提交
            Button button;

    @Bind(R.id.id_card_is)//身份证正面
            ImageView id_card_is;

    @Bind(R.id.id_card_back)//身份证反面
            ImageView id_card_back;
    @Bind(R.id.business_license)//营业执照
            ImageView business_license;

    Context context;
    String Judge_interface="0";//判断哪个接口   0、获取商户类型 1、上传图片 2、申请 3、查看修改内容 4、修改详情
    boolean Judge=false;

    private MyProgressDialog mDialog;
    List<MerchantsTypeModel> type=new ArrayList<>();
    List<ApplicationModel> list=new ArrayList<>();
    private DisplayImageOptions options;
    private ImageLoader imageLoader;
    String Judge_number="0";//判断哪个图片   0、身份证正面 1、身份证反面 3、营业执照
    String justimg="";//正面图片路径
    String backimg="";//反面图片路径
    String businessimg="";//营业执照
    private SelectPhotoPop selectPhotoPop;
    private  View  viewkre;
    String province ="";//省
    String city   ="";// 市
    String area ="";//  区
    String longitude ="";//   经度
    String latitude  ="";//  纬度
    String typeid="";
    String pos="0";//0、申请  1、修改
    String u_id="";
     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewkre= View.inflate(this, R.layout.activity_application, null);
        setContentView(viewkre);
        ButterKnife.bind(this);
        context=this;
        initView();
    }

    private void initView() {
        retur.setOnClickListener(this);
        button.setOnClickListener(this);
        id_card_is.setOnClickListener(this);
        id_card_back.setOnClickListener(this);
        business_license.setOnClickListener(this);
        merchants_type_layout.setOnClickListener(this);
        provincial_layou.setOnClickListener(this);
        options = ImgUtils.imageOptions();
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(context));
        if(getIntent()!=null){
            pos=getIntent().getStringExtra("pos");
            if (pos.equals("1")){
               u_id=getIntent().getStringExtra("id");
            }

        }
        if (pos.equals("1")){
            businesses ();
        }else {
            merchanttype();
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.retur:
                finish();
                break;
            case R.id.id_card_is:
                processadd("0");
                break;
            case R.id.id_card_back:
                processadd("1");
                break;
            case R.id.business_license:
                processadd("2");
                break;

            case R.id.merchants_type_layout:
                if (type.size()>0){
                    processtype();
                }else {
                    Judge=true;
                    merchanttype();
                }
                break;
            case R.id.provincial_layou:
                Intent intent = new Intent(context, SelectTheAddressActivity.class);
                intent.putExtra("pos","1");
                startActivityForResult(intent, Constant.APPLICATION);
                break;
                  		/* 注释  相机*/
            case R.id.item_popupwindows_camera:
                selectPhotoPop.dismiss();
                GalleryFinal.openCamera(Constant.CAMERA, MyApplication.getInstance().initGalley(Constant.CAMERA,1), mOnHanlderResultCallback);
                break;
            /* 注释  相册*/
            case R.id.item_popupwindows_Photo:
                selectPhotoPop.dismiss();
                GalleryFinal.openGallerySingle(Constant.GALLERYSINGLE, MyApplication.getInstance().initGalley(Constant.GALLERYSINGLE,1), mOnHanlderResultCallback);
                break;
            /* 注释  取消*/
            case R.id.item_popupwindows_cancel:
                selectPhotoPop.dismiss();
                break;
            case R.id.button:
                if (TextUtils.isEmpty(merchants_type_text.getText().toString().trim())){//商户类型
                    ToastUtils.show(context, getResources().getString(R.string.please_type));
                    return;
                }
                if (TextUtils.isEmpty(name.getText().toString().trim())){//商户名称
                    ToastUtils.show(context, getResources().getString(R.string.please_name));
                    return;
                }
                if (TextUtils.isEmpty(legal_name.getText().toString().trim())){//法人姓名
                    ToastUtils.show(context, getResources().getString(R.string.please_legal_name));
                    return;
                }
                if (TextUtils.isEmpty(id_number.getText().toString().trim())){//身份证号
                    ToastUtils.show(context, getResources().getString(R.string.please_id_number));
                    return;
                }
               if (!Sundry.personIdValidation(id_number.getText().toString())){//正确的身份证号
                    ToastUtils.show(this,getResources().getString(R.string.please_correct_id_number));
                    return;
                }
                if (TextUtils.isEmpty(mobilephone.getText().toString().trim())){//手机号
                    ToastUtils.show(context, getResources().getString(R.string.please_phone_number));
                    return;
                }
                if (!Sundry.isMobileNO(mobilephone.getText().toString().trim())){//验证手机号
                    ToastUtils.show(context, getResources().getString(R.string.please_correctness_phone_number));
                    return;
                }
                if (TextUtils.isEmpty(mail_box.getText().toString().trim())){//邮箱
                    ToastUtils.show(context, getResources().getString(R.string.please_box));
                    return;
                }
                if (!Sundry.checkEmail(mail_box.getText().toString().trim())){//邮箱
                    ToastUtils.show(context, getResources().getString(R.string.please_correctness));
                    return;
                }

                if (TextUtils.isEmpty(justimg)){//身份证正面
                    ToastUtils.show(context, getResources().getString(R.string.please_front));
                    return;
                }
                if (TextUtils.isEmpty(backimg)){//身份证反面
                    ToastUtils.show(context, getResources().getString(R.string.please_reverse));
                    return;
                }
                if (TextUtils.isEmpty(businessimg)){//营业执照
                    ToastUtils.show(context, getResources().getString(R.string.please_busines));
                    return;
                }
                if (TextUtils.isEmpty(provincial.getText().toString().trim())){//省市区
                    ToastUtils.show(context, getResources().getString(R.string.please_select_address));
                    return;
                }
                if (TextUtils.isEmpty(specific_address.getText().toString().trim())){//详细地址
                    ToastUtils.show(context, getResources().getString(R.string.specific_address));
                    return;
                }
                if (pos.equals("0")){
                    processapplybusiness();
                }else {
                    processmodifieddata();
                }

                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("stringmd5="+requestCode+"resultCode="+resultCode);
        if (resultCode==Constant.APPLICATION){
            if (requestCode==Constant.APPLICATION){
                specific_address.setText(data.getStringExtra("address"));
                province =data.getStringExtra("province");//省
                city =data.getStringExtra("city");// 市
                area =data.getStringExtra("district");//  区
                longitude =data.getStringExtra("longitude");//   经度
                latitude  =data.getStringExtra("latitude");//  纬度
                provincial.setText(province+","+city+","+area);
            }
        }
    }
    //调用相机
private void processadd(String pos){
    if (!PermissionsChecker.getPermissionsChecker(this, "0", 0)) {
        if (!PermissionsChecker.getPermissionsChecker(this, "0", 2)) {
            Judge_number=pos;
            showSelectPicPop();
        } else {
            ToastUtils.show(context, "请检查是否打开储存权限");
        }
    } else {
        ToastUtils.show(context, "请检查是否打开相机权限");
    }
}
    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            Bitmap bitmap = PictureUtil.decodeSampledBitmapFromFile(resultList.get(0).getPhotoPath(), 400, 400);
            String conimg  =PictureUtil.saveBitmapFile(bitmap, String.valueOf(0));
            processupload(conimg);
        }
        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {

        }
    };
    //相册
    private void showSelectPicPop() {
        selectPhotoPop = new SelectPhotoPop(this, this);
        selectPhotoPop.showAtLocation(viewkre, Gravity.BOTTOM, 0, 0);
    }


    //绑定类型
    private  void processtype(){
        MerchantsTypePhotoPop typephoto=new MerchantsTypePhotoPop(context,type);
        typephoto.showAtLocation(viewkre, Gravity.BOTTOM, 0, 0);
        typephoto.setAddresskListener(new MerchantsTypePhotoPop.OnAddressCListener() {
            @Override
            public void onClick(String province) {
//                System.out.println("stringmd5result"+province);
                merchants_type_text.setText(province);
                for (int i=0;i<type.size();i++){
                    if (province.equals(type.get(i).getTypename())){
                        typeid=type.get(i).getId();
                    }
                }
            }
        });
    }


    //上传图片
    private void processupload(String upload ){
        if (Sundry.isOpenNetwork(context)){
            Judge_interface="1";
            mDialog =new MyProgressDialog(context);
            HttpClient.upload(upload,this);
        }else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }
    //商品类型
    private void merchanttype(){
        if (Sundry.isOpenNetwork(context)){
            if (!Judge_interface.equals("3")){
                mDialog =new MyProgressDialog(context);
            }
            Judge_interface="0";
            HttpClient.merchanttype(this);

        }else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }
    //申请商家
    private void processapplybusiness(){
        if (Sundry.isOpenNetwork(context)){
            Judge_interface="2";
            mDialog =new MyProgressDialog(context);
            HttpClient.applybusiness(name.getText().toString().trim(),typeid,legal_name.getText().toString().trim(),mobilephone.getText().toString().trim(),
                    province,city,area,specific_address.getText().toString().trim(),longitude,latitude,mail_box.getText().toString().trim(),
                    businessimg,justimg,backimg,invite.getText().toString().trim(),id_number.getText().toString().trim(),this);

        }else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }
    //商家查看
    private void businesses (){
        if (Sundry.isOpenNetwork(context)){
            Judge_interface="3";
            mDialog =new MyProgressDialog(context);
            HttpClient.shopdetails(u_id,this);
        }else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }
    //修改申请商家
    private void processmodifieddata(){
        if (Sundry.isOpenNetwork(context)){
            Judge_interface="4";
            mDialog =new MyProgressDialog(context);
            HttpClient.modifieddata(u_id,"2",name.getText().toString().trim(),typeid,legal_name.getText().toString().trim(),mobilephone.getText().toString().trim(),
                    province,city,area,specific_address.getText().toString().trim(),longitude,latitude,mail_box.getText().toString().trim(),
                    businessimg,justimg,backimg,invite.getText().toString().trim(),id_number.getText().toString().trim(),"",this);

        }else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }
    @Override
    public void onSuccess(String result) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        System.out.println("stringmd5result"+result);
        List<MerchantsTypeModel> getnote = JsonTools.getmerchanttype(result);
        if (getnote!=null||getnote.size()>0){
            String error = getnote.get(0).getError();
            String mssage = getnote.get(0).getMssage();
            if (error.equals("200")){

                String content = getnote.get(0).getResult();
                if (Judge_interface.equals("0")){//类型
                    type = JsonTools.gettype(content);
                    if (Judge){
                        processtype();
                    }
                }else if (Judge_interface.equals("1")){//图片
                    if (Judge_number.equals("0")){//身份证正面
                        justimg=content;
                        imageLoader.displayImage(Constant.HTTP+content, id_card_is, options);
                    }else  if (Judge_number.equals("1")){//身份证反面
                        backimg=content;
                        imageLoader.displayImage(Constant.HTTP+content, id_card_back, options);
                    }else if (Judge_number.equals("2")){//营业执照
                        businessimg=content;
                        imageLoader.displayImage(Constant.HTTP+content, business_license, options);
                    }
                }else if (Judge_interface.equals("2")){// 申请
                    finish();
                    ToastUtils.show(context, mssage);
                 }else if (Judge_interface.equals("3")) {//查看申请详情
                    list= JsonTools.getbusiness(content);

                    if (list!=null||list.size()>0){
                        processData();
                    }
                }else if (Judge_interface.equals("4")) {//修改申请商家
                    finish();
                    ToastUtils.show(context, mssage);
                }
            }else if (error.equals("105")){
                Intent intent = new Intent(context, LoginActivity.class);
                startActivity(intent);
                ToastUtils.show(context, mssage);
            }else {
                ToastUtils.show(context, mssage);
            }
        }
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onCancelled(CancelledException cex) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onFinished() {

    }
    //绑定数据
    private void processData(){
        ApplicationModel applicationModel = list.get(0);
        specific_address.setText(applicationModel.getSuite());
        province =applicationModel.getProvince();//省
        city =applicationModel.getCity();// 市
        area =applicationModel.getDist();//  区
        longitude =applicationModel.getLongitude();//   经度
        latitude  =applicationModel.getLatitude();//  纬度
        provincial.setText(province+","+city+","+area);
         justimg=applicationModel.getIdcardfront();//正面图片路径
        imageLoader.displayImage(Constant.HTTP+justimg, id_card_is, options);
         backimg=applicationModel.getIdcardreverse();//反面图片路径
        imageLoader.displayImage(Constant.HTTP+backimg, id_card_back, options);
        businessimg=applicationModel.getLicense();//营业执照
        imageLoader.displayImage(Constant.HTTP+businessimg, business_license, options);
        name.setText(applicationModel.getName());// 商户名称
         legal_name.setText(applicationModel.getLegalname());//法人代表
         mobilephone.setText(applicationModel.getPhone());// 电话
         mail_box.setText(applicationModel.getEmail());//邮箱
         invite.setText(applicationModel.getBeinvitedcode());//邀请
        id_number.setText(applicationModel.getIdcardno());//身份证号
        String type="";
        if (applicationModel.getMerchanttype().equals("1")){
            type="房产商家";
            typeid="1";
        }else if (applicationModel.getMerchanttype().equals("2")){
            type="购车商家";
            typeid="2";
        }else if (applicationModel.getMerchanttype().equals("3")){
            type="干洗商家";
            typeid="3";
        }else if (applicationModel.getMerchanttype().equals("4")){
            type="开锁商家";
            typeid="4";
        }else if (applicationModel.getMerchanttype().equals("5")){
            type="果蔬商家";
            typeid="5";
        }else if (applicationModel.getMerchanttype().equals("6")){
            type="苦力商家";
            typeid="6";
        }else if (applicationModel.getMerchanttype().equals("7")){
            type="快递商家";
            typeid="7";
        }else if (applicationModel.getMerchanttype().equals("8")){
            type="家政商家";
            typeid="8";
        }else if (applicationModel.getMerchanttype().equals("9")){
            type="洗车商家";
            typeid="9";
        }
        merchants_type_text.setText(type);
        merchanttype();
    }
}
